<template>
  <div class="add">
    <el-container>

      <el-header class="header">
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-button type="text">{{testType || '题型'}}</el-button><i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="(item,index) in testTypeList" :key="index" @click.native="testType = item.name">{{item.name}}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button type="text" style="margin-left: 10px" :disabled="!testType" @click="addQuestionInfo">添加 +</el-button>
        <span style="float: right">
          <div style="width: 300px;float: left;margin-right: 10px">
            <el-input v-model="query.name" placeholder="请输入试卷名称"></el-input>
          </div>
          <el-button type="info" @click="$refs.upload.dialogVisible = true"> 导入试卷 <i class="el-icon-upload2"></i> </el-button>
          <el-button type="danger" @click="downloadQ"> 导出试卷 <i class="el-icon-download"></i> </el-button>
          <el-button type="warning" @click="downloadPDF"> 导出PDF <i class="el-icon-refresh"></i> </el-button>
          <el-button type="primary" @click="submit"> 提交 <i class="el-icon-mobile"></i> </el-button>
        </span>
      </el-header>
      <el-main  class="main">
        <el-row ref="main">
          <el-row  :ref="'question-'+index" v-for="(item,index) in questionList" :key="index">
            <el-row>
              {{index+1}}、【{{item.testType}} | {{testTypeList.filter(it => it.name === item.testType)[0].fraction }}分】
              <el-button @click="questionList.splice(index,1)" type="text"><i class="el-icon-delete"></i></el-button>
            </el-row>
            <singleChoice :ref="'question-info-'+index" :index="index+1" :item="item" v-if="item.testType === '单选题'" />
            <multipleChoice :ref="'question-info-'+index" :index="index+1" :item="item" v-else-if="item.testType === '多选题'" />
            <judgeChoice :ref="'question-info-'+index" :index="index+1" :item="item" v-else-if="item.testType === '判断题'" />
            <nullChoice :ref="'question-info-'+index" :index="index+1" :item="item" v-else-if="item.testType === '填空题'" />
            <singleChoice :ref="'question-info-'+index" :index="index+1" :item="item" v-else-if="item.testType === '简答题'" />
          </el-row>
        </el-row>
      </el-main>
    </el-container>
    <upload ref="upload" @success=" res => questionList.push(...res)"/>
  </div>
</template>

<script>
  import singleChoice from './singleChoice'
  import multipleChoice from './multipleChoice'
  import judgeChoice from './judgeChoice'
  import nullChoice from './nullChoice'
  import upload from './upload'
  import downloadPDF from './downloadPDF'
  export default {
    name: 'add',
    props: [''],
    components: { singleChoice,multipleChoice,judgeChoice,nullChoice,upload },
    data() {
      return {
        testTypeList:[],
        testType: null,
        questionList:[],
        query:{
          name:''
        }
      }
    },
    computed: {},
    methods: {
      downloadPDF(){
        downloadPDF(this.$refs.main.$el,Date.now())
      },
      downloadQ(){
        let link = document.createElement("a");
        //对下载的文件命名
        link.href = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(JSON.stringify(this.questionList));
        link.download =  `${this.query.name}.json`;
        link.style='display:none'
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      },
      submit(){
        new Promise((rs,rj)=>{
          if(!this.query.name){
            rj()
          }
          this.questionList.map((item,index)=>{
            if(!this.$refs['question-info-'+index][0].isSuccess){
              rj(index+1)
            }
          })
          rs(true)
        }).then(()=>{
          this.save()
        }).catch((index)=>{
          console.log(index)
          let text = index ? `请填写完整第${index}题` : '请输入试卷名称'
          this.$message(text)
        })
      },
      save(){
        if(this.query.ids){
          this.$api.del('question_info',{questionId:this.query.ids},res=>{
            let question_cnt =this.query
            question_cnt.fraction =0
            delete question_cnt.userName
            this.questionList.map((item,index)=>{
              let question_info =  this.$refs['question-info-'+index][0]
              let cnt={
                ids:Date.now() + index,
                questionId:question_cnt.ids,
                indexs:index + 1,
                name:question_info.name,
                testType:item.testType,
                answer:question_info.answer
              }
              console.log(cnt)
              question_cnt.fraction += Number(this.testTypeList.filter(it => it.name === item.testType)[0].fraction)
              this.$api.add('question_info',cnt,res=>{})
            })
            this.$api.up('question',question_cnt,res=>{})
          })
        }else{
          let question_cnt = {
            ids: Date.now(),
            name:this.query.name,
            userId:this.$adminInfo().ids,
            fraction:0,
          }
          this.questionList.map((item,index)=>{
            let question_info =  this.$refs['question-info-'+index][0]
            let cnt={
              ids:Date.now() + index,
              questionId:question_cnt.ids,
              indexs:index + 1,
              name:question_info.name,
              testType:item.testType,
              answer:question_info.answer
            }
            console.log(cnt)
            question_cnt.fraction += Number(this.testTypeList.filter(it => it.name === item.testType)[0].fraction)
            this.$api.add('question_info',cnt,res=>{})
          })
          this.$api.add('question',question_cnt,res=>{
            this.query = question_cnt
          })
        }
      },
      addQuestionInfo(){
        this.questionList.push({
          ids:Date.now(),
          name:null,
          testType:this.testType,
          answer:this.testType === "多选题" ? [] : null
        })
      },
    },
    async mounted() {
      this.$api.get('testType',{$orderBY: {col:'ids'}},res=>{
        this.testTypeList=res
      })
      let query = this.$route.query
      if(query.ids) {
        this.query = query
        let cnt ={
          $where :{ questionId : query.ids },
          $orderBY: {
            col: 'indexs',
            methods:'ASC'
          }
        }
        this.$api.get('question_info',cnt,res=>{
          if(res){
            res.map(item=>{
              if(item.testType === '填空题'){
                item.question = item.name
              }else if( item.testType === '单选题' ){
                let name = JSON.parse(decodeURIComponent(atob(item.name)))
                item.A = name.A
                item.B = name.B
                item.C = name.C
                item.D = name.D
                item.question = name.question
              }else if( item.testType === '多选题' ){
                let name = JSON.parse(decodeURIComponent(atob(item.name)))
                item.A = name.A
                item.B = name.B
                item.C = name.C
                item.D = name.D
                item.question = name.question
                item.answer = item.answer.split(',')
              }else if( item.testType === '判断题' ){
                item.question = item.name
              }
            })
            this.questionList = res
          }
        })
      }
    },
    created() {
    },
    watch: {}
  }
</script>

<style scoped lang="scss">
  .add {
    .main {
      height: calc(100vh - 140px);
      overflow: auto;
    }
    .header {
      background-color: #ecf0f5;
      line-height: 60px;
      height: 60px;
    }
  }
</style>

